<template>
  <div class="app-container">
    <el-form class="basic-form" ref="form" :model="form" label-width="80px" :rules="rules">
      <el-form-item label="功能名称" prop="name">
        <el-input v-model="form.name"></el-input>
      </el-form-item>
      <el-form-item label="图标" :rules="[{ required: true, message: '请上传图标' }]">
        <el-upload
          class="avatar-uploader"
          action="https://jsonplaceholder.typicode.com/posts/"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="handleBefore"
          name="fileName"
        >
          <img v-if="icon" :src="icon" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="功能描述" prop="desc">
        <el-input
          type="textarea"
          :autosize="{ minRows: 2, maxRows: 4}"
          v-model="form.desc">
        </el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="handleSubmit(form)">立即创建</el-button>
        <el-button @click="handleReset()">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
export default {
  name: 'feature-edit',
  data() {
    return {
      rules: {
        name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
        icon: [{ required: true, message: '请上传图标', trigger: 'change' }],
        desc: [{ required: true, message: '请上传描述', trigger: 'blur' }]
      },
      form: {},
      icon: ''
    }
  },

  methods: {
    handleBefore(file) {
      this.icon = URL.createObjectURL(file);
    },
    handleAvatarSuccess(res, file) {
      this.icon = URL.createObjectURL(file.raw);
    },

    handleSubmit(form) {
      this.$refs['form'].validate((valid) => {
        if (!valid) return false;

        if (!this.icon) {
          this.$message.error('请上传图标');
          return false;
        }

        this.$router.go(-1);
      });
    },

    handleReset() {
      this.$refs['form'].resetFields();
    }
  }
}
</script>
<style lang="scss" scoped>
.basic-form {
  width: 460px;
  margin: 0 auto;
  transform: translateX(-80px);
}

.avatar-uploader {
  ::v-deep {
    .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }

    .el-upload:hover {
      border-color: #409EFF;
    }

    .avatar-uploader-icon {
      font-size: 24px;
      color: #8c939d;
      width: 48px;
      height: 48px;
      line-height: 48px;
      text-align: center;
    }
  }
}

.avatar {
  width: 48px;
  height: 48px;
  display: block;
}
</style>
